import { Injector } from '@angular/core';
import { FarrisDesignBaseComponent, } from '@farris/designer-element';
import { DgControl, DomService } from '@farris/designer-services';
import { ControlContextMenuItem } from '../../../../../entity/control-context-menu';

const CHILD_FILL_COMMAND = 'childContainerFill';

export class ChildContainerFillService {
    private domService: DomService;

    private cmpInstance: FarrisDesignBaseComponent;

    constructor(private injector: Injector, cmpInstance: FarrisDesignBaseComponent) {

        this.domService = this.injector.get(DomService);

        this.cmpInstance = cmpInstance;
    }
    /**
     * 组装子表填充菜单
     */
    public assembleChildFillMenu(menuConfig: ControlContextMenuItem[]): ControlContextMenuItem[] {

        // 只有内置卡片表单可以启用子表填充
        if (this.domService.module.templateId !== 'card-template') {
            menuConfig = menuConfig.filter(menu => menu.id !== CHILD_FILL_COMMAND);
            return menuConfig;
        }

        // 限定内容区域容器
        const className = this.cmpInstance.component.appearance && this.cmpInstance.component.appearance.class;
        if (!className || !className.includes('f-page-main')) {
            menuConfig = menuConfig.filter(menu => menu.id !== CHILD_FILL_COMMAND);
            return menuConfig;
        }
        // 限定容器下只能有一个区块节点（like-card-container）
        if (!this.cmpInstance.component.contents || this.cmpInstance.component.contents.length !== 1) {
            menuConfig = menuConfig.filter(menu => menu.id !== CHILD_FILL_COMMAND);
            return menuConfig;
        }
        const likeCardContainer = this.cmpInstance.component.contents[0];
        const likeCardContainerClassName = likeCardContainer.appearance && likeCardContainer.appearance.class;
        if (!likeCardContainerClassName || !likeCardContainerClassName.includes('f-struct-like-card') || !likeCardContainer.isLikeCardContainer || !likeCardContainer.contents || !likeCardContainer.contents.length) {
            menuConfig = menuConfig.filter(menu => menu.id !== CHILD_FILL_COMMAND);
            return menuConfig;
        }

        // 收集子表区域
        const childContainers = this.getChildContainers(likeCardContainer);
        if (!childContainers.length) {
            menuConfig = menuConfig.filter(menu => menu.id !== CHILD_FILL_COMMAND);
            return menuConfig;
        }

        // 判断当前是否已启用填充
        const childFillMenu = menuConfig.find(menu => menu.id === CHILD_FILL_COMMAND);
        childFillMenu.title = (className.includes('f-page-child-fill') ? '关闭' : '启用') + childFillMenu.title;
        childFillMenu.id = (className.includes('f-page-child-fill') ? 'close' : 'enable') + childFillMenu.id;

        return menuConfig;
    }


    /**
     * 提取子表区域容器
     * @param childParentContainer 子表区域父节点
     */
    public getChildContainers(childParentContainer: any): any[] {
        const childContainers = childParentContainer.contents.filter(container => {
            const className = container.appearance && container.appearance.class;
            if (!className || !className.includes('f-struct-wrapper') || container.type !== DgControl.ContentContainer.type) {
                return;
            }
            const firstChildContent = container.contents && container.contents.length ? container.contents[0] : null;
            const firstChildClass = firstChildContent && firstChildContent.appearance ? firstChildContent.appearance.class : '';
            const firstChildClassList = firstChildClass ? firstChildClass.split(' ') : [];

            // 子表三层Tab容器 container-section-tab  或者子表分组容器：container-section-componentRef  或者子表分组多视图容器：container-section-MultiViewContainer
            if (firstChildContent.type === DgControl.Section.type && (firstChildClassList.includes('f-section-in-main') || firstChildClassList.includes('f-section-in-mainsubcard'))) {
                if (firstChildContent.contents && firstChildContent.contents.length === 1) {
                    const grandEle = firstChildContent.contents[0];
                    if (grandEle.type === DgControl.Tab.type || grandEle.type === DgControl.ComponentRef.type || grandEle.type === DgControl.MultiViewContainer.type) {
                        return true;
                    }
                }
            }
        });

        return childContainers;
    }

    /**
     * 启用子表填充
     * @param parentContainer 子表父容器
     */
    public enableChildContainerFill(pageMainContainer: any) {
        // 1、从表内容区域增加样式
        const className = pageMainContainer.appearance && pageMainContainer.appearance.class;
        if (className && !className.includes('f-page-child-fill')) {
            pageMainContainer.appearance.class += ' f-page-child-fill';
        }

        //  2、子表区域
        const childParentContainer = pageMainContainer.contents[0];
        let childContainers = [];
        // 2.1子表的父容器是区块（f-struct-like-card）---场景是卡片模板
        if (childParentContainer.type === DgControl.ContentContainer.type && childParentContainer.appearance.class.includes('f-struct-like-card')) {
            if (!childParentContainer.appearance.class.includes('f-struct-like-card-child-fill')) {
                childParentContainer.appearance.class += ' f-struct-like-card-child-fill';
            }
            childContainers = this.getChildContainers(childParentContainer);
        } else {
            // 2.2 子表的父容器是分栏面板的主区域SplitterPane----场景是列卡
            childContainers = this.getChildContainers(pageMainContainer);
        }




        childContainers.forEach(container => {
            // 3、子表区域container增加样式
            const containerClassName = container.appearance && container.appearance.class;
            if (containerClassName && containerClassName.includes('f-struct-wrapper') && !containerClassName.includes('f-struct-wrapper-child')) {
                container.appearance.class += ' f-struct-wrapper-child';
            }

            // 4、分组面板Section启用填充
            const section = container.contents[0];
            if (section) {
                section.fill = true;
            }
            const sectionChild = section.contents[0];

            // 5.1、分组面板下是标签页
            if (sectionChild && sectionChild.type === DgControl.Tab.type) {
                // 5.1.1 标签页启用填充
                sectionChild.contentFill = true;

                //  5.1.2 标签页下的组件节点（ComponentRef)：子表关闭自动高度
                if (sectionChild.contents) {
                    sectionChild.contents.forEach(tabPage => {
                        const cmpRef = tabPage.contents && tabPage.contents.find(co => co.type === DgControl.ComponentRef.type);
                        if (cmpRef) {
                            this.modifyDataGridInChildFill(cmpRef, true);

                        }
                        const multiViewContainer = tabPage.contents && tabPage.contents.find(co => co.type === DgControl.MultiViewContainer.type);
                        if (multiViewContainer) {
                            this.modifyMultiViewContainerInChildFill(multiViewContainer, true);
                        }
                    });
                }


            }
            // 5.2、分组面板下是组件节点（ComponentRef)：子表关闭自动高度
            if (sectionChild && sectionChild.type === DgControl.ComponentRef.type) {
                this.modifyDataGridInChildFill(sectionChild, true);
            }
            // 5.2、分组面板下是组件节点（ComponentRef)：子表关闭自动高度
            if (sectionChild && sectionChild.type === DgControl.MultiViewContainer.type) {
                this.modifyMultiViewContainerInChildFill(sectionChild, true);
            }


        });


    }

    /**
     * 子表启用填充后，修改DataGrid组件的样式
     * @param componentRef 组件ref
     * @param flag 是否启用填充
     */
    private modifyDataGridInChildFill(componentRef: any, flag: boolean) {
        const gridComponent = this.domService.getComponentById(componentRef.component);
        if (!gridComponent || gridComponent.componentType !== 'dataGrid') {
            return;
        }
        const dataGridParentContainer = this.domService.selectNode(gridComponent, item => item.type === DgControl.ContentContainer.type &&
            item.contents && item.contents.length && item.contents[0].type === DgControl.DataGrid.type);

        switch (flag) {
            case true: {
                // 1、 确保子表DataGrid父容器要有f-grid-is-sub样式
                if (dataGridParentContainer) {
                    if (!dataGridParentContainer.appearance) {
                        dataGridParentContainer.appearance = { class: 'f-grid-is-sub  f-utils-flex-column' };
                    }
                    if (!dataGridParentContainer.appearance.class) {
                        dataGridParentContainer.appearance.class = 'f-grid-is-sub f-utils-flex-column';
                    }
                    if (!dataGridParentContainer.appearance.class.includes('f-grid-is-sub')) {
                        dataGridParentContainer.appearance.class += ' f-grid-is-sub';
                    }
                    if (!dataGridParentContainer.appearance.class.includes('f-utils-flex-column')) {
                        dataGridParentContainer.appearance.class += ' f-utils-flex-column';
                    }
                }

                // 2、 子表DataGrid要关闭自动高度、新增填充标识
                const dataGrid = this.domService.selectNode(gridComponent, item => item.type === DgControl.DataGrid.type);
                if (dataGrid) {
                    dataGrid.autoHeight = false;
                    dataGrid.isChildFill = true;
                }
                break;
            }
            case false: {
                // 1、 子表DataGrid移除填充标识
                const dataGrid = this.domService.selectNode(gridComponent, item => item.type === DgControl.DataGrid.type);
                if (dataGrid) {
                    delete dataGrid.isChildFill;
                }
            }
        }




    }

    /**
     * 若子表启用了多视图，则要修改多视图的样式
     * @param multiViewContainer 多视图节点
     * @param flag 是否启用填充
     */
    private modifyMultiViewContainerInChildFill(multiViewContainer: any, flag: boolean) {
        switch (flag) {
            case true: {
                // 多视图追加填充样式
                if (!multiViewContainer.appearance) {
                    multiViewContainer.appearance = { class: 'f-multiview-fill' };

                }
                if (!multiViewContainer.appearance.class) {
                    multiViewContainer.appearance.class = 'f-multiview-fill';
                }
                if (!multiViewContainer.appearance.class.includes('f-multiview-fill')) {
                    multiViewContainer.appearance.class += ' f-struct-wrapper-child';
                }

                // 修改多视图内部的DataGrid组件样式
                multiViewContainer.contents.forEach(viewItem => {
                    if (viewItem.contents && viewItem.contents.length) {
                        viewItem.contents.forEach(co => {
                            if (co.type === DgControl.ComponentRef.type) {
                                this.modifyDataGridInChildFill(co, true);
                            }
                        });
                    }
                });

                break;
            }
            case false: {

                if (multiViewContainer.appearance && multiViewContainer.appearance.class && multiViewContainer.appearance.class.includes('f-multiview-fill')) {
                    multiViewContainer.appearance.class = multiViewContainer.appearance.class.replace('f-multiview-fill', '').trim();
                }
                // 修改多视图内部的DataGrid组件样式
                multiViewContainer.contents.forEach(viewItem => {
                    if (viewItem.contents && viewItem.contents.length) {
                        viewItem.contents.forEach(co => {
                            if (co.type === DgControl.ComponentRef.type) {
                                this.modifyDataGridInChildFill(co, false);
                            }
                        });
                    }
                });
                break;
            }
        }


    }

    /**
     * 关闭子表填充
     * @param parentContainer 子表父容器
     */
    public closeChildContainerFill(pageMainContainer: any) {
        // 1、从表内容区域移除样式
        const className = pageMainContainer.appearance && pageMainContainer.appearance.class;
        if (className && className.includes('f-page-child-fill')) {
            pageMainContainer.appearance.class = pageMainContainer.appearance.class.replace('f-page-child-fill', '').trim();
        }

        //  2、子表区域
        const childParentContainer = pageMainContainer.contents[0];
        let childContainers = [];
        // 2.1子表的父容器是区块（f-struct-like-card）---场景是卡片模板
        if (childParentContainer.type === DgControl.ContentContainer.type && childParentContainer.appearance.class.includes('f-struct-like-card')) {
            if (childParentContainer.appearance.class.includes('f-struct-like-card-child-fill')) {
                childParentContainer.appearance.class = childParentContainer.appearance.class.replace('f-struct-like-card-child-fill', '').trim();
            }
            childContainers = this.getChildContainers(childParentContainer);
        } else {
            // 2.2 子表的父容器是分栏面板的主区域SplitterPane----场景是列卡
            childContainers = this.getChildContainers(pageMainContainer);
        }

        childContainers.forEach(container => {
            // 2、子表区域container移除样式
            const containerClassName = container.appearance && container.appearance.class;
            if (containerClassName && containerClassName.includes('f-struct-wrapper') && containerClassName.includes('f-struct-wrapper-child')) {
                container.appearance.class = container.appearance.class.replace('f-struct-wrapper-child', '').trim();
            }

            // 3、分组面板Section关闭填充
            const section = container.contents[0];
            if (section) {
                section.fill = false;
            }

            const sectionChild = section.contents[0];


            // 5.1、分组面板下是标签页
            if (sectionChild && sectionChild.type === DgControl.Tab.type) {
                // 5.1.1 标签页启用填充
                sectionChild.contentFill = false;

                //  5.1.2 标签页下的组件节点（ComponentRef)：子表关闭自动高度
                if (sectionChild.contents) {
                    sectionChild.contents.forEach(tabPage => {
                        const cmpRef = tabPage.contents && tabPage.contents.find(co => co.type === DgControl.ComponentRef.type);
                        if (cmpRef) {
                            this.modifyDataGridInChildFill(cmpRef, false);

                        }
                        const multiViewContainer = tabPage.contents && tabPage.contents.find(co => co.type === DgControl.MultiViewContainer.type);
                        if (multiViewContainer) {
                            this.modifyMultiViewContainerInChildFill(multiViewContainer, false);
                        }
                    });
                }


            }
            // 5.2、分组面板下是组件节点（ComponentRef)：子表关闭自动高度
            if (sectionChild && sectionChild.type === DgControl.ComponentRef.type) {
                this.modifyDataGridInChildFill(sectionChild, false);
            }
            // 5.2、分组面板下是组件节点（ComponentRef)：子表关闭自动高度
            if (sectionChild && sectionChild.type === DgControl.MultiViewContainer.type) {
                this.modifyMultiViewContainerInChildFill(sectionChild, false);
            }
        });


    }
}
